package cn.com.wangluotongxin.merchants.database;

import cn.com.wangluotongxin.admin.DAdminMerchantsInfoService;
import cn.com.wangluotongxin.admin.vo.DMerchantsInfoVo;
import cn.com.wangluotongxin.common.pojo.TenantInfo;
import cn.com.wangluotongxin.db.config.TenantMybatisPlusConfig;
import cn.com.wangluotongxin.redis.cache.TenantCacheService;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Slf4j
@Component
public class MerchantsDatabaseService {

    @Reference
    private DAdminMerchantsInfoService merchantsInfoService;

    @Autowired
    private TenantCacheService tenantCacheService;

    /**
     *  加载租户信息
     */
    public void loadDatabase() {
        List<DMerchantsInfoVo> dMerchantsInfoVos = merchantsInfoService.getAvailableMerchantsDatabase();
        log.info("加载商户资源库信息:{}", dMerchantsInfoVos.size());
        for(DMerchantsInfoVo vo : dMerchantsInfoVos){
            if(StrUtil.isBlank(vo.getDLinkUrl())) continue;
            TenantMybatisPlusConfig.load(vo.getId().toString(), vo.getDLinkUrl(), vo.getDUsername(), vo.getDPassword());
            TenantMybatisPlusConfig.run();

            TenantInfo tenantInfo = new TenantInfo();
            tenantInfo.setKey(vo.getId().toString());
            tenantInfo.setTenantNo(vo.getMerchantsNo());
            tenantInfo.setTenantName(vo.getName());
            tenantCacheService.setTenant(vo.getId().toString(), tenantInfo);
        }
    }

    public void loadDatabase(Integer merchantsId) {
        DMerchantsInfoVo vo = merchantsInfoService.getAvailableMerchantsDatabase(merchantsId);
        if(vo == null) return;
        log.info("重新加载合作商缓存信息:{}", vo.getName());
        if(StrUtil.isBlank(vo.getDLinkUrl())) return;
        TenantMybatisPlusConfig.load(vo.getId().toString(), vo.getDLinkUrl(), vo.getDUsername(), vo.getDPassword());
        TenantMybatisPlusConfig.run();

        TenantInfo tenantInfo = new TenantInfo();
        tenantInfo.setKey(vo.getId().toString());
        tenantInfo.setTenantNo(vo.getMerchantsNo());
        tenantInfo.setTenantName(vo.getName());
        tenantCacheService.setTenant(vo.getId().toString(), tenantInfo);
    }

    public TenantInfo getTenantInfo(Integer tenantId) {
        if(tenantId == null) return null;
        TenantInfo tenantInfo = tenantCacheService.getTenant(tenantId.toString());
        if(tenantInfo != null) return tenantInfo;
        this.loadDatabase(tenantId);
        ThreadUtil.sleep(500);
        tenantInfo = tenantCacheService.getTenant(tenantId.toString());
        return tenantInfo;
    }
}
